import NumberUtils from '@/utils/NumberUtils';
import { Input, Dropdown, Menu } from 'antd'
import { useEffect } from 'react';
import { useState } from 'react';


const NumberInput = (props) => {

    const {
        autoCompleteOptions,
        value,
        defaultValue,
        onChange,
        onBlur,
        style,
        onSelect,
        onPressEnter
    } = props;

    const [dropDownVisiable, setDropDownVisiable] = useState(false)
    const [realValue, setRealValue] = useState(defaultValue)

    useEffect(() => {
        setRealValue(value || defaultValue || 0)
    }, [value])

    const onValueChange = (e) => {
        const { value } = e.target;
        if (NumberUtils.isNumber(value) || value === '' || value === '0.') {
            setRealValue(value)
            if (onChange) {
                onChange(value);
            }
        } else {
            setRealValue(realValue)
        }
    }

    const onInputPressEnter = () => {
        if (onPressEnter) {
            onPressEnter(realValue)
        }
    }

    if (!autoCompleteOptions) {
        return <Input style={style} value={realValue} onChange={onValueChange} onPressEnter={onInputPressEnter}></Input>
    }

    const onInputBlur = () => {
        if (onBlur) {
            onBlur();
        }
    }


    const autoCompleteOptionsRender = autoCompleteOptions && (<Menu
        onClick={(e) => {
            setDropDownVisiable(false)
            setRealValue(e.key)
            if (onSelect) {
                onSelect(e.key)
            }
        }}
    >
        {autoCompleteOptions.map(item => <Menu.Item key={item.value}>{item.name || item.value}</Menu.Item>)}
    </Menu>)

    return (
        <Dropdown
            visible={dropDownVisiable}
            overlay={autoCompleteOptionsRender}>
            <Input
                onPressEnter={onInputPressEnter}
                style={style}
                value={realValue}
                onChange={onValueChange}
                onFocus={() => {
                    setDropDownVisiable(true)
                }}
                onBlur={onInputBlur}
            ></Input>
        </Dropdown>
    )
}

export default NumberInput